/**
 * Copyright 2008 Matthew DeLambo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.delambo.drool.pooling;

import com.delambo.drool.interfaces.*;
import java.sql.*;

/**
 * Houses a datasource for a pool and instantiates and returns connections.
 * @author delambo
 */
public final class DataSource_Impl implements DataSource {
    final private Driver driver;
    final private String database, db_username, db_pass;
    final private Logger logger;
        
    public DataSource_Impl(Driver driver, String db, String db_u, String db_p, 
            Logger logger) {
        this.driver = driver;
        this.database = db;
        this.db_username = db_u;
        this.db_pass = db_p;
        this.logger = logger;
        this.loadDriver();
    }
   
    /**
     * Returns an instantiated connection.
     * @return new connection.
     */
    public Connection get() {
        try {
            return DriverManager.getConnection(database, db_username, db_pass);
        } catch (Exception ex) { logger.all("", ex); return null; }
    }

    /**
     * De-registers a driver.
     */
    public void unLoadDriver() {
        try {
            DriverManager.deregisterDriver(driver);
        } catch (Exception e) { logger.all("Failed unLoadDriver: ", e); }
    }
    
    /**
     * Registers a driver.
     */
    private void loadDriver() {
        try {
            DriverManager.registerDriver(this.driver);
	} catch (Exception e) { logger.all("Loading Driver: ", e); }
    }
}
